package com.mavenq.fly.utils.excelv2;

import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;

import java.io.*;
import java.util.*;



// 使用示例
public class ExcelUtilDemo {
    
    public static void main(String[] args) {
        try {
            new ExcelUtilDemo().runDemo();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void runDemo() throws Exception {
        // 1. 基础导出示例
        exportBasicDemo();
        
        // 2. 高级导出示例
        exportAdvancedDemo();
        
        // 3. 基础导入示例
        importBasicDemo();
        
        // 4. 列互换导入示例
        importColumnMappingDemo();
        
        // 5. 高级导入示例
        importAdvancedDemo();
    }
    
    private void exportBasicDemo() throws FileNotFoundException {
        System.out.println("=== 基础导出示例 ===");
        
        List<User> userList = Arrays.asList(
            new User("张三", 25, "zhangsan@example.com", new Date()),
            new User("李四", 30, "lisi@example.com", new Date()),
            new User("王五", 28, "wangwu@example.com", new Date())
        );
        
        String[] headers = {"姓名", "年龄", "邮箱", "创建时间"};
        String[] fieldNames = {"name", "age", "email", "createTime"};
        
        FileOutputStream fos = new FileOutputStream("basic_export.xlsx");
        ExcelUtil.exportToExcel(userList, headers, fieldNames, "用户列表", fos, true);
        
        System.out.println("基础导出完成: basic_export.xlsx");
    }
    
    private void exportAdvancedDemo() throws FileNotFoundException {
        System.out.println("=== 高级导出示例 ===");
        
        List<User> userList = Arrays.asList(
            new User("张三", 25, "zhangsan@example.com", new Date()),
            new User("李四", 30, "lisi@example.com", new Date())
        );
        
        String[] headers = {"用户姓名", "用户年龄", "电子邮箱", "注册时间"};
        String[] fieldNames = {"name", "age", "email", "createTime"};
        
        ExcelExportConfig config = new ExcelExportConfig();
        config.setHeaderBgColor(IndexedColors.DARK_BLUE);
        config.setHeaderFontSize((short) 16);
        config.setHeaderRowHeight((short) 600);
        config.setDataRowHeight((short) 450);
        config.setDefaultColumnWidth(20);
        config.setWrapText(true);
        config.setDataAlignment(HorizontalAlignment.CENTER);
        
        FileOutputStream fos = new FileOutputStream("advanced_export.xlsx");
        ExcelUtil.exportToExcelAdvanced(userList, headers, fieldNames, "用户列表", fos, true, config);
        
        System.out.println("高级导出完成: advanced_export.xlsx");
    }
    
    private void importBasicDemo() throws FileNotFoundException {
        System.out.println("=== 基础导入示例 ===");
        
        FileInputStream fis = new FileInputStream("basic_export.xlsx");
        String[] headers = {"姓名", "年龄", "邮箱", "创建时间"};
        String[] fieldNames = {"name", "age", "email", "createTime"};
        
        List<User> users = ExcelUtil.importFromExcel(fis, headers, fieldNames, User.class, true);
        users.forEach(user -> System.out.println("导入: " + user));
    }
    
    private void importColumnMappingDemo() throws FileNotFoundException {
        System.out.println("=== 列互换导入示例 ===");
        
        FileInputStream fis = new FileInputStream("basic_export.xlsx");
        
        // 即使Excel列顺序变化，也能正确映射
        ExcelImportConfig<User> config = new ExcelImportConfig<>(User.class)
            .columnMapping("姓名", "name")     // Excel中的"姓名"列映射到name字段
            .columnMapping("年龄", "age")      // Excel中的"年龄"列映射到age字段  
            .columnMapping("邮箱", "email")    // Excel中的"邮箱"列映射到email字段
            .columnMapping("创建时间", "createTime") // Excel中的"创建时间"列映射到createTime字段
            .importListener(new ImportListener<User>() {
                @Override
                public void onRowImported(User obj, int rowIndex) {
                    System.out.println("成功导入第 " + (rowIndex+1) + " 行: " + obj.getName());
                }
                
                @Override
                public void onComplete(int successCount, int errorCount) {
                    System.out.println("导入完成: 成功 " + successCount + " 条, 失败 " + errorCount + " 条");
                }
            });
        
        List<User> users = ExcelUtil.importExcel(fis, config, true);
        System.out.println("列互换导入完成，共导入 " + users.size() + " 条数据");
    }
    
    private void importAdvancedDemo() throws FileNotFoundException {
        System.out.println("=== 高级导入示例 ===");
        
        FileInputStream fis = new FileInputStream("basic_export.xlsx");
        
        ExcelImportConfig<User> config = new ExcelImportConfig<>(User.class)
            .columnMapping("姓名", "name")
            .columnMapping("年龄", "age") 
            .columnMapping("邮箱", "email")
            .columnMapping("创建时间", "createTime")
            .customConverter("age", (value, targetType) -> {
                // 自定义年龄转换器
                if (value instanceof Number) {
                    int age = ((Number) value).intValue();
                    // 年龄范围验证
                    if (age < 0 || age > 150) {
                        throw new RuntimeException("年龄必须在0-150之间");
                    }
                    return age;
                }
                return 0;
            })
            .strictHeaderCheck(false)
            .importListener(new ImportListener<User>() {
                @Override
                public void onRowError(int rowIndex, Exception e) {
                    System.err.println("第 " + (rowIndex+1) + " 行导入失败: " + e.getMessage());
                }
            });
        
        List<User> users = ExcelUtil.importExcel(fis, config, true);
        System.out.println("高级导入完成，共导入 " + users.size() + " 条数据");
    }

    // 实体类
    static class  User {
        private String name;
        private Integer age;
        private String email;
        private Date createTime;
        private Boolean status;

        // 构造方法
        public User() {}

        public User(String name, Integer age, String email, Date createTime) {
            this.name = name;
            this.age = age;
            this.email = email;
            this.createTime = createTime;
            this.status = true;
        }

        // getter and setter
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }

        public Integer getAge() { return age; }
        public void setAge(Integer age) { this.age = age; }

        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }

        public Date getCreateTime() { return createTime; }
        public void setCreateTime(Date createTime) { this.createTime = createTime; }

        public Boolean getStatus() { return status; }
        public void setStatus(Boolean status) { this.status = status; }

        @Override
        public String toString() {
            return "User{name='" + name + "', age=" + age + ", email='" + email + "'}";
        }
    }
}